import Ember from 'ember';
import {
  calculateSelected
}
from '../utils/mlist-util';
//minus-square-o

export default Ember.Mixin.create({
  selectedState: Ember.computed('model.@each.isSelected', function() {
    return calculateSelected(this.get('model'));
  }),
  pluralModelName: Ember.computed('modelName', function() {
    var modelName = this.get('modelName');
    if (!modelName) {
      alert("please add 'modelName' property to list controller.");
    }
    return Ember.Inflector.inflector.pluralize(modelName);
  }),
  editHandler() {
    var modellist = this.get('model'),
      pluralModelName = this.get('pluralModelName');

    var selectedOne = modellist.find((it) => {
      return it.get('isSelected');
    });
    this.transitionToRoute(pluralModelName + ".edit", selectedOne);
  },
  createHandler() {
    var pluralModelName = this.get('pluralModelName');
    this.transitionToRoute(pluralModelName + ".new");
  },
  defaultMenuHandler(mname) {
    if (mname === 'edit') {
      this.editHandler();
    } else if (mname === 'create') {
      this.createHandler();
    }
  },
  commonMenus: [{
    name: 'create',
    action: "create",
    label: "新增",
    showWhen: "always"
  }, {
    name: 'delete',
    action: "delete",
    label: "删除",
    showWhen: "some"
  }, {
    name: 'edit',
    action: "edit",
    label: "编辑",
    showWhen: "one"
  }],
  meta: Ember.computed('model', function() {
    var modelName = this.get('modelName');
    if (!modelName) {
      alert("please add modelName property in list controller!");
    }
    var meta = this.store.metadataFor(modelName);
    return meta;
  }),
  page: 0,
  size: Ember.computed('meta', function() {
    var meta = this.get('meta');
    return meta.pageSize || 20;
  }),
  q: "",
  afterListChanged() {
    console.log('observer called in list-view-mixin');
    var modellist = this.get('model');
    if (modellist) {
      modellist.forEach((it) => {
        if (it.get('isSelected')) {
          it.set('isSelected', false);
        }
      });
    }
  },
  listChanged: Ember.observer('page', 'q','size', function() {
    Ember.run.once(this, 'afterListChanged');
  })
});
